package com.hzwq.service;

import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.util.Log;

import com.hzwq.appkeepalive.MainActivity;
import com.hzwq.appkeepalive.R;

import static androidx.core.app.NotificationCompat.PRIORITY_MAX;

/**
 * 描 述：
 * 作 者：kanglanlan  2021/3/25 14:22
 * 修改描述： XXX
 * 修 改 人： XXX  2021/3/25 14:22
 * 修改版本： XXX
 */
public class BackGroundService extends Service {
    String CHANNEL_ONE_ID = "CHANNEL_ONE_ID";
    String CHANNEL_ONE_NAME= "CHANNEL_ONE_ID";
    Notification notification;
    private Context mContext;
    private static Thread uploadGpsThread;
    private MediaPlayer bgmediaPlayer;
    private boolean isrun = true;

    public BackGroundService() {
    }

    @SuppressLint("WrongConstant")
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        NotificationChannel notificationChannel= null;
//进行8.0的判断
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            notificationChannel= new NotificationChannel(CHANNEL_ONE_ID,
                    CHANNEL_ONE_NAME, NotificationManager.IMPORTANCE_HIGH);
            notificationChannel.enableLights(true);
            notificationChannel.setLightColor(Color.RED);
            notificationChannel.setShowBadge(true);
            notificationChannel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
            NotificationManager manager= (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
            manager.createNotificationChannel(notificationChannel);
        }
        mContext = this;

        Intent notificationIntent = new Intent(this, MainActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(mContext, 0,
                notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        //1.通知栏占用，不清楚的看官网或者音乐类APP的效果
        notification = new Notification.Builder(mContext)
                .setSmallIcon(R.drawable.ic_launcher_background)
                .setWhen(System.currentTimeMillis())
                .setTicker("GPS测试")
                .setContentTitle("GPS测试标题")
                .setContentText("GPS测试内容")
                .setOngoing(true)
                .setPriority(PRIORITY_MAX)
                .setContentIntent(pendingIntent)
                .setAutoCancel(false)
                .build();
        /*使用startForeground,如果id为0，那么notification将不会显示*/
        startForeground(0, notification);

        //2.开启线程（或者需要定时操作的事情）
        if(uploadGpsThread == null){
            uploadGpsThread = new Thread(new Runnable() {
                @Override
                public void run() {
                    //这里用死循环就是模拟一直执行的操作
                    while (isrun){

                        //你需要执行的任务
//                        doSomething();
                        Log.d("程序保活===", "服务");

                        try {
                            Thread.sleep(10000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            });
            uploadGpsThread.start();
        }

        //3.最关键的神来之笔，也是最投机的动作，没办法要骗过CPU
        //这就是播放音乐类APP不被杀的做法，自己找个无声MP3放进来循环播放
        if(bgmediaPlayer == null){
            bgmediaPlayer = MediaPlayer.create(this,R.raw.slient);
            bgmediaPlayer.setLooping(true);
            bgmediaPlayer.start();
        }

        return START_STICKY;
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public void onDestroy() {
//        isrun = false;
//        stopForeground(true);
//        bgmediaPlayer.release();
//        stopSelf();
        super.onDestroy();
        Log.d("程序保活===", "停止服务");
//        stopPlayMusic();
// 重启自己
        Intent intent = new Intent(getApplicationContext(), BackGroundService.class);
        startService(intent);
    }
}